package com.zrrd.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrrd.reggie.bean.Dish;
import com.zrrd.reggie.bean.DishFlavor;
import com.zrrd.reggie.bean.dto.DishDto;
import com.zrrd.reggie.mapper.DishMapper;
import com.zrrd.reggie.service.DishFlavorService;
import com.zrrd.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;
    @Override
    @Transactional
    public void saveDish(DishDto dto) {
        dto.setSort(1);
        this.save(dto);
        List<DishFlavor> flavors=dto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dto.getId());
        }
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public DishDto getDishWithFlavors(Long id) {
        Dish dish = this.getById(id);
        DishDto dto=new DishDto();
        BeanUtils.copyProperties(dish,dto);
        QueryWrapper<DishFlavor> wrapper=new QueryWrapper<>();
        wrapper.eq("dish_id",id);
        List<DishFlavor> list = dishFlavorService.list(wrapper);
        dto.setFlavors(list);
        return dto;
    }

    @Override
    public void updateDishWithFlavors(DishDto dto) {
        this.updateById(dto);
        QueryWrapper<DishFlavor> wrapper=new QueryWrapper<>();
        wrapper.eq("dish_id",dto.getId());
        dishFlavorService.remove(wrapper);
        List<DishFlavor> flavors = dto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dto.getId());
        }
        dishFlavorService.saveBatch(flavors);
    }
}
